<template>
  <div class="layout-container main reset-styles">
    <el-card shadow="always" class="card">
      <div>
        <div style="padding-bottom: 20px">
          <el-page-header :icon="ArrowLeft" @back="backToProblem">
            <template #content>
              <div class="flex items-center">
                <span class="text-large font-600 mr-3"> {{ problemTitle }} </span>
                <el-tag :style="{ backgroundColor: '#f5f5f5', color: difficultyColor,marginLeft: '5px' }">
                  {{ difficultyText }}
                </el-tag>
              </div>
            </template>
          </el-page-header>
        </div>
        <div class="list">
          <el-descriptions border :column="4">
            <!-- 第一行：4列 -->
            <el-descriptions-item label="提交">
              <el-icon name="el-icon-data-line"/>
              <span>{{ commitNum }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="通过">
              <el-icon name="el-icon-circle-check"/>
              <span>{{ passNum }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="时间">
              <el-icon name="el-icon-time"/>
              <span>{{ time }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="内存">
              <el-icon name="el-icon-memory"/>
              <span>{{ memory }}</span>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <el-divider/>
      <div v-loading="isLoading" :element-loading-text="'提交中...'" ref="editContainer" class="code-editor"></div>
      <el-divider/>
      <div class="flex-container">
        <div class="header-container">
          <el-select v-model="selectedLanguage" @change="updateLanguage" class="select" size="default">
            <el-option v-for="option in options" :key="option.value" :label="option.label"
                       :value="option.value"></el-option>
          </el-select>
        </div>
        <div>
          <el-button size="large" class="next3" type="primary" @click="submitForm">提交代码</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>


<script setup>
import {getCurrentInstance, ref, onMounted, nextTick, computed, watch, watchEffect} from 'vue';
import * as monaco from 'monaco-editor/esm/vs/editor/editor.main.js';
import JsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
import axios from "axios";
import {ElMessage} from "element-plus";
import router from '@/router';
import {useStore} from "vuex";
import {useRoute} from "vue-router";
import {ArrowLeft, ArrowLeftBold} from "@element-plus/icons-vue";

const problemDetails = ref("");
const isLoading = ref(false);
// Vuex store 的使用
const store = useStore();
const {proxy} = getCurrentInstance();
const problemTitle = computed(() => problemDetails.value ? `${problemDetails.value.codeId}.${problemDetails.value.title}` : '');
const difficultyText = computed(() => problemDetails.value ? problemDetails.value.difficultyName : '未知');
const difficultyColor = computed(() => {
  switch (difficultyText.value) {
    case '简单':
      return '#1cb8b8'; // 绿色
    case '中等':
      return '#e6a23c'; // 黄色
    case '困难':
      return '#f56c6c'; // 红色
    default:
      return '#f5f5f5'; // 默认灰色
  }
});


const tags = computed(() => problemDetails.value ? problemDetails.value.tags : []);
const commitNum = computed(() => problemDetails.value ? problemDetails.value.commitNum : '0');
const passNum = computed(() => problemDetails.value ? problemDetails.value.passNum : '0');
const memory = computed(() => problemDetails.value ? problemDetails.value.memoryLimit : '未知');
const time = computed(() => problemDetails.value ? problemDetails.value.timeLimit : '未知');

// Monaco Editor 全局环境配置
self.MonacoEnvironment = {
  getWorker() {
    return new JsonWorker();
  },
};

const selectedLanguage = ref('C++');
let monacoEditor = null;

onMounted(async () => {
  await nextTick();

  // Load problem details
  await loadProblemDetails();

  // Use a computed property to manage the result data
  const result = computed(() => store.state.results[route.params.id]);

  // Optional console log to check the result
  console.log(result.value);

  // Define a computed property for submission details
  const submissionDetails = computed(() => result.value ? result.value.resultData : null);

  // Optional console log to check submission details
  console.log(submissionDetails.value);

  watchEffect(() => {
    // Initialize local variables to manage the state
    let language = 'cpp'; // Default language is cpp

    if (submissionDetails.value) {
      // Check and adjust the language based on the submission details
      if (submissionDetails.value.data.language === "C++") {
        language = "cpp";
      } else {
        language = submissionDetails.value.data.language;
      }

      if (!monacoEditor) {
        // Ensure that Monaco Editor is initialized only if it has not been initialized before
        monacoEditor = monaco.editor.create(proxy.$refs.editContainer, {
          value: submissionDetails.value.data.code || '',
          readOnly: false,
          language: language,
          theme: 'vs',
          selectOnLineNumbers: true,
          renderSideBySide: false,
        });
      } else {
        // Update the editor with new code and language if already initialized
        monacoEditor.setValue(submissionDetails.value.data.code);
        selectedLanguage.value = language;
        updateLanguage();
      }
    } else {
      // If no submission details are available, ensure Monaco Editor is usable
      if (!monacoEditor) {
        monacoEditor = monaco.editor.create(proxy.$refs.editContainer, {
          value: '',
          readOnly: false,
          language: 'cpp',
          theme: 'vs',
          selectOnLineNumbers: true,
          renderSideBySide: false,
        });
      }
    }
  });
});


const route = useRoute();
const loadProblemDetails = async () => {
  const id = route.params.id; // 从 Vuex 获取问题 ID
  const api = `/oj/ProblemsGroup/problems/${id}`;
  try {
    const response = await axios.get(api);
    problemDetails.value = response.data.data;  // 假设返回的数据在 data.data 中
  } catch (error) {
    console.error('Error loading problem details:', error);
    ElMessage.error('Failed to load problem details');
  }
};

const submitForm = async () => {
  if (isLoading.value) return;
  isLoading.value = true; // 请求开始，显示加载动画
  // 在发送之前，检查和转换语言标识符
  let languageToSend = selectedLanguage.value;
  if (languageToSend === 'cpp') {
    languageToSend = 'C++'; // 将 'cpp' 转换为 'C++'
  }

  const postData = {
    problemId: problemDetails.value.id,
    code: monacoEditor.getValue(),
    language: languageToSend // 使用转换后的语言标识符
  };

  try {
    const response = await axios.post(`/oj/commit/oj`, postData, {
      headers: {
        'token': localStorage.getItem('token')
      }
    });

    if (response.data.code === 500) {
      ElMessage.error(response.data.msg || 'Server error');
    } else {
      await store.dispatch('storeResult', {
        id: problemDetails.value.id,
        data: {
          resultData: response.data,
          problemDetails: problemDetails.value
        }
      });

      // 确保在跳转前关闭加载动画
      isLoading.value = false;

      router.push({
        path: `/student/oj/CommitResult/${problemDetails.value.id}`
      });
    }
  } catch (error) {
    isLoading.value = false; // 即便失败也要记得关闭加载动画
    console.error('Network or server error:', error);
    ElMessage.error('Network or server error');
  }
};


const backToProblem = () => {
  router.push(`/student/oj/problem-detail/${problemDetails.value.id}`)
}
// 语言选项和更新函数
const options = [
  {label: "C++", value: 'cpp'}, // 将 'C++' 改为 'cpp'
  {label: 'JavaScript', value: 'javascript'}, // 确保使用 Monaco 支持的语言标识符
  {label: 'Python3', value: 'python'}, // 应为 'python'
  {label: 'Java', value: 'java'}
];


const updateLanguage = () => {
  if (monacoEditor && monacoEditor.getModel()) {
    monaco.editor.setModelLanguage(monacoEditor.getModel(), selectedLanguage.value);
  }
};


</script>


<style scoped>
.next3 {
  float: right;
}

.code-editor {
  height: 50vh;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.select {
  width: 15vh;
}

.reset-styles {
  all: initial;
}

.text-large {
  font-size: 20px; /* 更大的字体尺寸 */
}

.font-600 {
  font-weight: 600; /* 中等偏上的粗细 */
}

.main {
  padding-top: 20px;
}

::v-deep blockquote {
  background-color: #f9f9f9;
  border-left: 5px solid #ccc;
  padding: 0.5em 10px;
  margin: 1em 0;
  box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
}

::v-deep .hljs, ::v-deep blockquote {
  font-family: 'Courier New', Courier, monospace;
  color: #333;
}

::v-deep .hljs {
  background-color: #f7f7f7;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 10px;
  box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
  overflow-x: auto;
}

.flex-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.select {
  width: 15vh;
}
</style>

